package com.zl.tby.service.impl;

import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyWeatherQuery;
import com.zl.tby.model.TbyEcologyInfo;
import com.zl.tby.model.TbyFireRating;
import com.zl.tby.model.TbyMonitoringStation;
import com.zl.tby.model.TbyWeather;
import com.zl.tby.repository.TbyEcologyInfoRepo;
import com.zl.tby.screen.service.ITbyEcologyInfoScreenService;
import com.zl.tby.screen.vo.ecology.TbyEcologyScreenInfo;
import com.zl.tby.service.ITbyEcologyInfoService;
import com.zl.tby.service.ITbyFireRatingService;
import com.zl.tby.service.ITbyWeatherService;
import com.zl.tby.vo.TbyWeatherForm;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.annotation.Db;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 生态因子 接口实现类
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Slf4j
@Component
public class TbyEcologyInfoServiceImpl implements ITbyEcologyInfoService {

    @Db
    private TbyEcologyInfoRepo tbyEcologyInfoRepo;
    @Inject
    private ITbyFireRatingService tbyFireRatingService;
    @Inject
    private ITbyWeatherService tbyWeatherService;
    @Inject
    private ITbyEcologyInfoScreenService tbyEcologyInfoScreenService;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyEcologyInfo> add(TbyEcologyInfo entity) {
        // 保证一个小时只有一条数据
        entity.setCreateBy(-1L);
        entity.setCreateTime(LocalDateTime.now());
        // 新增数据
        long id = tbyEcologyInfoRepo.insert(entity, true);
        entity.setId(id);
        // 修改数据
        // tbyEcologyInfoRepo.updateById(entity, true);

        return R.ok(entity);
    }

    @Tran
    @Override
    public R<TbyEcologyInfo> update(TbyEcologyInfo entity) {
        entity.setUpdateBy(0L);
        entity.setUpdateTime(LocalDateTime.now());
        tbyEcologyInfoRepo.updateById(entity, true);
        return R.ok(entity);
    }

    /**
     * 查询数据库中是否有匹配项
     * @author AnWeiNan
     * @date 2024/11/6 上午10:26
     */
    @Override
    public List<TbyEcologyInfo> selectByIdTime(Long stationId, Date modifiedDate) {
        List<TbyEcologyInfo> dbList = this.tbyEcologyInfoRepo.selectList(mp -> {
            mp.whereEq("station_id", stationId).andEq("report_date", modifiedDate);
        });

        // 如果查询到的结果为空，返回一个空列表；否则返回查询结果
        return dbList.isEmpty() ? Collections.emptyList() : dbList;
    }

    @Override
    public void autoCalculateRealWeather() {
        String reportDate = ToolsUtil.dateUtil2String(new Date(), "yyyy-MM-dd HH") + ":00:00";
        String date = ToolsUtil.dateUtil2String(new Date(), "yyyy-MM-dd");
        String column = "avg(temperature) as temperature, avg(humidity) as humidity, avg(rain) as rain, avg(lux) as lux_decimal"
                    + ", avg(wind_speed) as wind_speed"
                    + ", avg(beam) as beam, avg(pressure) as pressure, max(wind_direction) as wind_direction";
        try {
            List<TbyEcologyScreenInfo> dataList = db.table("tby_ecology_info")
                    .whereEq("report_date", reportDate)
                    .selectList(column, TbyEcologyScreenInfo.class);
            if (dataList == null || dataList.size() == 0) {
                return;
            }
            TbyEcologyScreenInfo ecology = dataList.get(0);
            if (ecology.getTemperature() == null) {
                log.error("当前小时无数据");
                return;
            }
            TbyFireRating entity = this.tbyFireRatingService.get();
            boolean add = false;
            if (entity == null) {
                add = true;
                entity = new TbyFireRating();
            }
            entity.setWeather(ToolsUtil.getWeatherText(ecology.getRain(), ecology.getLuxDecimal()));
            // 紫外线等级
            entity.setUltravioletRays(ToolsUtil.getLuxLevel(ecology.getLuxDecimal()));
            // 温度
            entity.setTemperature(ecology.getTemperature().setScale(1, BigDecimal.ROUND_HALF_UP));
            // 湿度
            entity.setHumidity(ecology.getHumidity().setScale(1, BigDecimal.ROUND_HALF_UP));
            // 风向
            entity.setWindDirection(ToolsUtil.windDirectionSwitch((float) ecology.getWindDirection()));
            dataList = db.table("tby_ecology_info").whereTrue()
                    .andIf(true, "report_date >= ?", date + " 00:00:00")
                    .andIf(true, "report_date <= ?", date + " 23:59:59")
                    .selectList("avg(pm_one) as pm_one_decimal", TbyEcologyScreenInfo.class);
            entity.setAqi("-");
            if (dataList != null && dataList.size() > 0) {
                ecology = dataList.get(0);
                if (ecology.getPmOneDecimal() != null) {
                    entity.setAqi(ToolsUtil.getAQI(ecology.getPmOneDecimal()));
                }
            }
            // 获取站点为9的站
            TbyEcologyScreenInfo screenInfo = this.tbyEcologyInfoScreenService.detailByStationId(9L);
            if (screenInfo != null) {
                entity.setWindDirection(screenInfo.getWindDirectionText());
            }
            if (add) {
                this.tbyFireRatingService.add(entity);
            } else {
                this.tbyFireRatingService.update(entity);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("自动计算实时天气异常：", ex);
        }
    }

    @Override
    public boolean autoCalculateDayWeather(String date) {
        String column = "max(temperature) as high_temperature, min(temperature) as low_temperature , avg(temperature) as temperature"
                        + ", sum(rain) as rain, avg(wind_speed) as wind_speed, max(wind_direction) as wind_direction"
                        + ", avg(lux) as lux_decimal, avg(pm_one) as pm_one_decimal, avg(humidity) as humidity";
        try {
            List<TbyEcologyScreenInfo> dataList = db.table("tby_ecology_info").whereTrue()
                    .andIf(true, "report_date >= ?", date + " 00:00:00")
                    .andIf(true, "report_date <= ?", date + " 23:59:59")
                    .selectList(column, TbyEcologyScreenInfo.class);
            if (dataList == null || dataList.size() == 0) {
                return false;
            }
            if (dataList.get(0).getTemperature() == null) {
                return false;
            }
            TbyEcologyScreenInfo ecology = dataList.get(0);
            TbyWeatherQuery query = new TbyWeatherQuery();
            List<String> dateArray = new ArrayList<>();
            dateArray.add(date);
            query.setDateArray(dateArray);
            // today是查询今天， 如果不查今天，这个可以随意传
            query.setType("day");
            List<TbyWeatherForm> weatherFormList = this.tbyWeatherService.list(query);
            TbyWeatherForm entity;
            boolean add = false;
            if (weatherFormList != null && weatherFormList.size() > 0) {
                entity = weatherFormList.get(0);
            } else {
                add = true;
                entity = new TbyWeatherForm();
            }
            entity.setWeatherDateFormat(date);
            entity.setWeather(ToolsUtil.getWeatherText(ecology.getRain(), ecology.getLuxDecimal()));
            // 紫外线等级
            entity.setUltravioletRays(ToolsUtil.getLuxLevel(ecology.getLuxDecimal()));
            // 温度
            entity.setHighTemperature(ecology.getHighTemperature().setScale(1, BigDecimal.ROUND_HALF_UP));
            entity.setLowTemperature(ecology.getLowTemperature().setScale(1, BigDecimal.ROUND_HALF_UP));
            entity.setAgvTemperature(ecology.getTemperature().setScale(1, BigDecimal.ROUND_HALF_UP));
            // 湿度
            entity.setHumidity(ecology.getHumidity().setScale(1, BigDecimal.ROUND_HALF_UP));
            // 风向
            entity.setWindDirection(ToolsUtil.windDirectionSwitch((float) ecology.getWindDirection()));
            entity.setWindSpeed(ecology.getWindSpeed().setScale(1, BigDecimal.ROUND_HALF_UP));
            entity.setWindPower(ToolsUtil.getWindPower(entity.getWindSpeed()));
            // 降水量
            entity.setPrecipitation(ecology.getRain().setScale(1, BigDecimal.ROUND_HALF_UP));
            entity.setAqi(ToolsUtil.getAQI(ecology.getPmOneDecimal()));
            // 获取站点为9的站
            TbyEcologyScreenInfo screenInfo = this.tbyEcologyInfoScreenService.detailByStationId(9L);
            if (screenInfo != null) {
                entity.setWindDirection(screenInfo.getWindDirectionText());
            }
            if (add) {
                log.info("新增" + date + "天气信息");
                this.tbyWeatherService.add(entity);
                return true;
            } else {
                log.info("修改" + date + "天气信息");
                this.tbyWeatherService.update(entity);
                return false;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            log.error("自动计算日天气信息异常", ex);
        }
        return false;
    }
}
